package com.suneast.suneaststore.modules.goodsdetail;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextWatcher;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.util.SparseArray;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.suneast.suneaststore.R;
import com.suneast.suneaststore.modules.goodsdetail.adapter.SpecsChooseAdapter;
import com.suneast.suneaststore.modules.goodsdetail.adapter.SpecsItemAdapter;
import com.suneast.suneaststore.bean.goodsdetail.ItemShopCart2UpLoading;
import com.suneast.suneaststore.bean.goodsdetail.RelativeBean;
import com.suneast.suneaststore.bean.goodsdetail.SpecsDataBean;
import com.suneast.suneaststore.modules.goodsdetail.event.ConfirmGoodsEvent;
import com.suneast.suneaststore.modules.goodsdetail.event.GotSpecsDataEvent;
import com.suneast.suneaststore.modules.goodsdetail.event.SpecsItemCheckChanged;
import com.suneast.suneaststore.bean.shopcart.ItemGoodsInShopCart;
import com.suneast.suneaststore.ui.customview.ZzCheckBox;
import com.suneast.suneaststore.util.dimen.ScreenUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class SelectParameterDialog extends Dialog implements View.OnClickListener {

    private static final String TAG = "test";

    private static int cartId = 0;

    public static void setCartId(int id) {
        cartId = id;
    }

    public static int getCartId() {
        return cartId;
    }

    public SelectParameterDialog(Context context, GotSpecsDataEvent specsData) {
        super(context, R.style.specs_dialog);
        initData(context, specsData);
        initView();
    }

    private ImageView goodsImg;
    private TextView specsTv;
    private ImageButton minusBtn;
    private TextView goodsCountTv;
    private EditText widthEdit;
    private EditText heightEdit;
    private RadioGroup buyTypeRG;

    private SpecsChooseAdapter specsChooseAdapter;

    private int type = 0;// type 0 : 加入购物车  1: 立即购买  2：选择商品规格/颜色 3.购物车中修改商品规格
    private double width = 0f;
    private double height = 0f;
    private int count = 1;
    private int specsTypeCount = 0;
    private boolean onlyOneSku = false;
    private List<SpecsDataBean.SpecsBean.ItemsBean> selectedSpecsIdList;

    public int getType() {
        return type;
    }

    public void setType(int type) {
        this.type = type;
    }

    private Context context;
    private SpecsDataBean.GoodsBean goodsBean;
    private List<SpecsDataBean.OptionsBean> optionsBeanList;
    private List<SpecsDataBean.SpecsBean> specsBeanList;
    private SparseArray<SparseArray<RelativeBean>> relativeSparses;
    private ItemShopCart2UpLoading itemShopCart;

    private void initData(Context context, GotSpecsDataEvent specsData) {
        this.context = context;
        goodsBean = specsData.getData().getGoods();
        optionsBeanList = specsData.getData().getOptions();
        specsBeanList = specsData.getData().getSpecs();
        relativeSparses = specsData.getRelativeSparses();
        itemShopCart = new ItemShopCart2UpLoading(goodsBean.getId(),
                goodsBean.getMerchid(), goodsBean.getWindowsize(),
                goodsBean.getUnit(),
                goodsBean.getWindowsize() == 1,
                1);
        specsTypeCount = specsBeanList.size();
        selectedSpecsIdList = new ArrayList<>(specsTypeCount);
        onlyOneSku = optionsBeanList.size() == 1;
    }

    private void initView() {
        final View view = View.inflate(context, R.layout.dialog_select_parameter, null);
        initChildView(view);//初始化子控件
        view.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT));
        setContentView(view);
        Window window = getWindow();
        if (window != null) {
            getWindow().setGravity(Gravity.BOTTOM);
            WindowManager.LayoutParams attributes = getWindow().getAttributes();
            attributes.width = ScreenUtil.getDialogScreenWidth(context);
            attributes.height = (int) (ScreenUtil.getScreenHeight(context) * 0.75f);
            getWindow().setAttributes(attributes);//设置 dialog 宽度为全屏宽
        }
    }

    @Override
    public void setOnShowListener(@Nullable OnShowListener listener) {
        super.setOnShowListener(listener);
    }

    private void initChildView(View rootView) {
        goodsImg = rootView.findViewById(R.id.img_goods);
        Glide.with(context).load(goodsBean.getThumb()).into(goodsImg);
        TextView priceTv = rootView.findViewById(R.id.tv_price);
        TextView discountPriceTv = rootView.findViewById(R.id.tv_discount_price);
        TextView stockTv = rootView.findViewById(R.id.tv_stock);
        specsTv = rootView.findViewById(R.id.tv_specification);
        ImageButton exitBtn = rootView.findViewById(R.id.btn_dismiss_dialog);
        exitBtn.setOnClickListener(this);
        TextView goodsCountTipTv = rootView.findViewById(R.id.tv_tip_of_goods_count);
        goodsCountTipTv.setText(String.format(context.getResources()
                .getString(R.string.number_with_unit), goodsBean.getUnit()));
        minusBtn = rootView.findViewById(R.id.btn_minus);
        minusBtn.setOnClickListener(this);
        goodsCountTv = rootView.findViewById(R.id.tv_goods_count);
        ImageButton plusBtn = rootView.findViewById(R.id.btn_plus);
        plusBtn.setOnClickListener(this);
        RecyclerView specsRV = rootView.findViewById(R.id.rv_goods_specification);
        Button confirmBtn = rootView.findViewById(R.id.btn_confirm_specification);
        confirmBtn.setOnClickListener(this);

        String mPrice = String.valueOf(goodsBean.getMemberprice());
        String d2Price = String.valueOf(goodsBean.getD2_price());
        String d2Discount = String.valueOf(goodsBean.getD2_discount());
        String unitStr = goodsBean.getUnit();
        String memberPriceStr = String.format(context.getResources().getString(R.string.member_price_normal), mPrice, unitStr);
        String discountPriceStr = String.format(context.getResources().getString(R.string.discount_price_normal), d2Price, unitStr, d2Discount, unitStr);
        Spannable memberSpan = new SpannableString(memberPriceStr);
        memberSpan.setSpan(new AbsoluteSizeSpan(40), 0, 1 + mPrice.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        memberSpan.setSpan(new ForegroundColorSpan(Color.RED), 0, 1 + mPrice.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        priceTv.setText(memberSpan);

        if (Double.valueOf(goodsBean.getD2_discount()) > 0) {
            Spannable dSpan = new SpannableString(discountPriceStr);
            int secondStartPos = discountPriceStr.indexOf("+");
            dSpan.setSpan(new AbsoluteSizeSpan(40), 0, 1 + d2Price.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            dSpan.setSpan(new ForegroundColorSpan(Color.RED), 0, 1 + d2Price.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            dSpan.setSpan(new AbsoluteSizeSpan(40), secondStartPos, secondStartPos + d2Discount.length() + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            dSpan.setSpan(new ForegroundColorSpan(Color.RED), secondStartPos, secondStartPos + d2Discount.length() + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            discountPriceTv.setText(dSpan);
        } else {
            discountPriceTv.setVisibility(View.INVISIBLE);
        }

        if (goodsBean.getTotal() > 0) {
            stockTv.setText(String.format(context.getResources().getString(R.string.stock_state),
                    String.valueOf(goodsBean.getTotal()), unitStr));
        } else {
            stockTv.setVisibility(View.INVISIBLE);
        }

        if (goodsBean.getWindowsize() != 0) {//需要输入窗户宽高
            LinearLayout widthHeightLayout = rootView.findViewById(R.id.layout_width_height);
            widthHeightLayout.setVisibility(View.VISIBLE);
            LinearLayoutCompat windowSizeLine = rootView.findViewById(R.id.line_size);
            windowSizeLine.setVisibility(View.VISIBLE);
            widthEdit = rootView.findViewById(R.id.edit_window_width);
            heightEdit = rootView.findViewById(R.id.edit_window_height);
            widthEdit.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void afterTextChanged(Editable s) {
                    if (s.length() > 0) {
                        if (s.length() == 1 && ".".equals(s.toString())) {
                            width = 0;
                        } else {
                            width = Double.valueOf(s.toString());
                        }
                    } else {
                        width = 0;
                    }
                    itemShopCart.setWidth(width);
                }
            });
            heightEdit.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void afterTextChanged(Editable s) {
                    if (s.length() > 0) {
                        if (s.length() == 1 && ".".equals(s.toString())) {
                            height = 0;
                        } else {
                            height = Double.valueOf(s.toString());
                        }
                    } else {
                        height = 0;
                    }
                    itemShopCart.setHeight(height);
                }
            });
        }
        if (goodsBean.getTotal_buy() == 1) {//需要显示整卷购买或零售的单选按钮
            LinearLayout buyTypeLayout = rootView.findViewById(R.id.layout_how_to_buy);
            buyTypeLayout.setVisibility(View.VISIBLE);
            LinearLayoutCompat buyTypeLine = rootView.findViewById(R.id.line_buy_type);
            buyTypeLine.setVisibility(View.VISIBLE);
            buyTypeRG = rootView.findViewById(R.id.rg_how_to_buy);
            buyTypeRG.setOnCheckedChangeListener((RadioGroup radioGroup, int checkedId) -> {
                if (checkedId == R.id.rb_retail) {
                    itemShopCart.setSuit(false);
                } else if (checkedId == R.id.rb_total_buy) {
                    itemShopCart.setSuit(false);
                }
            });
        }
        specsRV.setLayoutManager(new LinearLayoutManager(context));
        specsChooseAdapter = new SpecsChooseAdapter(R.layout.item_specs_choose,
                specsBeanList);
        specsChooseAdapter.bindToRecyclerView(specsRV);
    }

    public void setSpecs(ItemGoodsInShopCart item) {
        if (itemShopCart != null && item != null) {
            itemShopCart.setOptionId(item.getOptionId());
            itemShopCart.setCount(item.getTotal());
            goodsCountTv.setText(String.valueOf(item.getTotal()));
            if (item.isCustom()) {
                itemShopCart.setCustom(item.isCustom());
                itemShopCart.setWidth(item.getWidth());
                itemShopCart.setHeight(item.getHeight());
                if (widthEdit != null) {
                    widthEdit.setText(String.valueOf(itemShopCart.getWidth()));
                }
                if (heightEdit != null) {
                    heightEdit.setText(String.valueOf(itemShopCart.getHeight()));
                }
            }
            if (item.isSuit()) {
                itemShopCart.setSuit(item.isSuit());
                if (buyTypeRG != null) {
                    buyTypeRG.check(R.id.rb_total_buy);
                }
            }
            itemShopCart.setInstall(item.isInstall());
            itemShopCart.setProcess(item.isMachining());
            String specsStr = findSpecsStrByOptionId(item.getOptionId());
            if (specsStr != null && specsStr.length() > 0) {
                itemShopCart.setOptionTitle(specsStr);
                if (specsTypeCount == 1) {
                    int itemId = Integer.valueOf(specsStr);
                    SpecsDataBean.SpecsBean.ItemsBean itemsBean = findItemsBean(itemId);
                    if (itemsBean != null) {
                        setCheckedByItemBean(itemsBean);
                        EventBus.getDefault().post(new SpecsItemCheckChanged(true, itemsBean));
                    }
                } else {
                    String[] specsIdStrs = specsStr.split("_");
                    for (int i = 0, iLength = specsIdStrs.length; i < iLength; i++) {
                        int itemId = Integer.valueOf(specsIdStrs[i]);
                        SpecsDataBean.SpecsBean.ItemsBean itemsBean = findItemsBean(itemId);
                        if (itemsBean != null) {
                            setCheckedByItemBean(itemsBean);
                            EventBus.getDefault().post(new SpecsItemCheckChanged(true, itemsBean));
                        }
                    }
                }
            }
        }
    }

    private String findSpecsStrByOptionId(int optionId) {
        for (int i = 0, length = optionsBeanList.size(); i < length; i++) {
            if (optionsBeanList.get(i).getId() == optionId) {
                return optionsBeanList.get(i).getSpecs();
            }
        }
        return "";
    }

    private SpecsDataBean.SpecsBean.ItemsBean findItemsBean(int itemId) {
        for (int i = 0, iLength = specsBeanList.size(); i < iLength; i++) {
            for (int j = 0, jLength = specsBeanList.get(i).getItems().size(); j < jLength; j++) {
                SpecsDataBean.SpecsBean.ItemsBean itemsBean = specsBeanList.get(i).getItems().get(j);
                if (itemsBean.getItemid() == itemId) {
                    return itemsBean;
                }
            }
        }
        return null;
    }

    private void setCheckedByItemBean(SpecsDataBean.SpecsBean.ItemsBean item) {
        int curPos = getItemAdapterPos(item.getLevel());
        SpecsItemAdapter curAdapter = specsChooseAdapter.getItemAdapterList().get(curPos);
        for (int i = 0, iLength = curAdapter.getData().size(); i < iLength; i++) {
            SpecsDataBean.SpecsBean.ItemsBean itemsBean = curAdapter.getData().get(i);
            if (itemsBean != null && itemsBean.getItemid() == item.getItemid()) {
                ZzCheckBox cb = (ZzCheckBox) curAdapter.getViewByPosition(i, R.id.cb_specs);
                if (cb != null) {
                    cb.setChecked(true);
                }
            }
        }
    }

    @Override
    public void onAttachedToWindow() {
        super.onAttachedToWindow();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDetachedFromWindow() {
        EventBus.getDefault().unregister(this);
        super.onDetachedFromWindow();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_dismiss_dialog: {
                hide();
            }
            break;
            case R.id.btn_minus: {
                if (count > 1) {
                    count--;
                    itemShopCart.setCount(count);
                    goodsCountTv.setText(String.valueOf(count));
                    if (count == 1) {
                        minusBtn.setEnabled(false);
                    }
                }
            }
            break;
            case R.id.btn_plus: {
                if (count >= goodsBean.getTotal()) {
                    Toast.makeText(context, "数量超出范围~", Toast.LENGTH_SHORT).show();
                } else {
                    count++;
                    itemShopCart.setCount(count);
                    goodsCountTv.setText(String.valueOf(count));
                    if (!minusBtn.isEnabled()) {
                        minusBtn.setEnabled(true);
                    }
                }
            }
            break;
            case R.id.btn_confirm_specification: {
                if (isSelectedAllParams()) {
                    Log.e(TAG, "onClick: getOptionId = " + itemShopCart.getOptionId());
                    if (itemShopCart.getOptionId() != 0) {
                        EventBus.getDefault().post(new ConfirmGoodsEvent(type, itemShopCart));
                        hide();
                    } else {
                        Toast.makeText(context, "内部规格错误", Toast.LENGTH_SHORT).show();
                    }
                }
            }
            break;
        }
    }

    private boolean isSelectedAllParams() {
        if (!isSelectAllSpecs() && !onlyOneSku) {
            Toast.makeText(context, "规格未选择完全", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (goodsBean.getWindowsize() > 0) {
            if (itemShopCart.getHeight() <= 0 || itemShopCart.getWidth() <= 0) {
                Toast.makeText(context, "请填写窗户的宽高", Toast.LENGTH_SHORT).show();
                return false;
            }
        }
        return true;
    }

    //如果用户选全了所有属性则做如下操作
    private void doAfterSelectAllSpecs() {
        String specsStr = connectSpecsStr();
        SpecsDataBean.OptionsBean optionsBean = findOptionsBean(specsStr);
        if (optionsBean != null) {
            //将此optionId赋值给 itemShopCart
            itemShopCart.setOptionId(optionsBean.getId());
            itemShopCart.setOptionTitle(optionsBean.getTitle());
            //设置选择的sku文字
            setSpecsTv(optionsBean.getTitle());
            String thumb = optionsBean.getThumb();
            if (thumb != null && thumb.length() > 0) {
                //加载对应的sku的图片
                Glide.with(context).load(thumb).into(goodsImg);
            }
        } else {
            itemShopCart.setOptionId(0);
            itemShopCart.setOptionTitle("");
            setSpecsTv("");
        }
    }

    private void setSpecsTv(String text) {
        specsTv.setText(String.format(
                context.getResources().getString(R.string.selected_format),
                text));
    }

    //根据给定的商品属性id数组,判断是否选全了属性
    private boolean isSelectAllSpecs() {
        return selectedSpecsIdList.size() == specsTypeCount;
    }

    //拼接属性标志字符
    private String connectSpecsStr() {
        switch (specsTypeCount) {
            case 1: {
                if (selectedSpecsIdList.size() == 1) {
                    return String.valueOf(selectedSpecsIdList.get(0).getItemid());
                }
            }
            break;
            case 2: {
                if (selectedSpecsIdList.size() == 2) {
                    if (selectedSpecsIdList.get(0).getLevel()
                            < selectedSpecsIdList.get(1).getLevel()) {
                        return selectedSpecsIdList.get(0).getItemid() + "_"
                                + selectedSpecsIdList.get(1).getItemid();
                    } else {
                        return selectedSpecsIdList.get(1).getItemid() + "_"
                                + selectedSpecsIdList.get(0).getItemid();
                    }
                }
            }
            break;
            case 3: {
                if (selectedSpecsIdList.size() == 3) {
                    int[] ids = new int[3];
                    for (int i = 0; i < selectedSpecsIdList.size(); i++) {
                        SpecsDataBean.SpecsBean.ItemsBean bean = selectedSpecsIdList.get(i);
                        switch (bean.getLevel()) {
                            case 3: {
                                ids[0] = bean.getItemid();
                                break;
                            }
                            case 1: {
                                ids[1] = bean.getItemid();
                                break;
                            }
                            case 2: {
                                ids[2] = bean.getItemid();
                                break;
                            }
                        }
                    }
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0, length = ids.length; i < length; i++) {
                        sb.append(ids[i]);
                        if (i != length - 1) {
                            sb.append("_");
                        }
                    }
                    return sb.toString();
                }
            }
            break;
        }
        return "error";
    }

    //根据给定的属性标志字符串 返回 OptionsBean
    private SpecsDataBean.OptionsBean findOptionsBean(String specs) {
        for (int i = 0, iLength = optionsBeanList.size(); i < iLength; i++) {
            SpecsDataBean.OptionsBean bean = optionsBeanList.get(i);
            if (specs.equals(bean.getSpecs())) {
                return bean;
            }
        }
        return null;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCheckChanged(SpecsItemCheckChanged event) {
        if (event.isChecked()) {
            SpecsDataBean.SpecsBean.ItemsBean curItem = event.getItem();
            switch (specsTypeCount) {
                case 1: {// 该商品只有一种属性类别
                    if (selectedSpecsIdList.size() == 0) {
                        selectedSpecsIdList.add(curItem);
                    } else {
                        selectedSpecsIdList.set(0, curItem);
                        updateCurSelectRow(curItem);
                    }
                }
                break;
                case 2: {// 该商品有两种属性类别
                    switch (selectedSpecsIdList.size()) {
                        case 0: {
                            selectedSpecsIdList.add(curItem);
                            updateOtherRow(curItem, getItemAdapterPos(3 - curItem.getLevel()));
                        }
                        break;
                        case 1: {
                            if (selectedSpecsIdList.get(0).getLevel() == curItem.getLevel()) {
                                selectedSpecsIdList.set(0, curItem);
                                updateCurSelectRow(curItem);
                                updateOtherRow(curItem, getItemAdapterPos(3 - curItem.getLevel()));
                            } else {
                                selectedSpecsIdList.add(curItem);
                            }
                        }
                        break;
                        case 2: {
                            if (selectedSpecsIdList.get(0).getLevel() == curItem.getLevel()) {
                                selectedSpecsIdList.set(0, curItem);
                                updateCurSelectRow(curItem);
                                updateOtherRow(curItem, getItemAdapterPos(3 - curItem.getLevel()));
                            } else if (selectedSpecsIdList.get(1).getLevel() == curItem.getLevel()) {
                                selectedSpecsIdList.set(1, curItem);
                                updateCurSelectRow(curItem);
                            }
                        }
                        break;
                    }
                }
                break;
                case 3: {// 该商品有三种属性类别
                    switch (selectedSpecsIdList.size()) {
                        case 0: {
                            selectedSpecsIdList.add(curItem);
                            updateOtherTwoRow(curItem);
                        }
                        break;
                        case 1: {
                            if (curItem.getLevel() == selectedSpecsIdList.get(0).getLevel()) {
                                selectedSpecsIdList.set(0, curItem);
                                //更新本行
                                updateCurSelectRow(curItem);
                                //更新其他两行
                                updateOtherTwoRow(curItem);
                            } else {
                                selectedSpecsIdList.add(curItem);
                                //根据第一 二个选择的行的属性组合 更新第三个待选择的行
                                updateThirdRowByTwoBean(selectedSpecsIdList.get(0), selectedSpecsIdList.get(1));
                            }
                        }
                        break;
                        case 2: {
                            if (curItem.getLevel() == selectedSpecsIdList.get(0).getLevel()) {
                                selectedSpecsIdList.set(0, curItem);
                                // 更新本行
                                updateCurSelectRow(curItem);
                                int adapterPos = getItemAdapterPos(selectedSpecsIdList.get(1).getLevel());
                                //更新第二次选择的行
                                updateOtherRow(curItem, adapterPos);
                                // 如果第二次选择的行仍有匹配 和一组合 更新第三个选择的行
                                if (stillHasChecked(adapterPos)) {
                                    updateThirdRowByTwoBean(selectedSpecsIdList.get(0), selectedSpecsIdList.get(1));
                                }
                            } else if (curItem.getLevel() == selectedSpecsIdList.get(1).getLevel()) {
                                selectedSpecsIdList.set(1, curItem);
                                //更新本行
                                updateCurSelectRow(curItem);
                                //和一组合 更新第三个待选择的行
                                updateThirdRowByTwoBean(selectedSpecsIdList.get(0), selectedSpecsIdList.get(1));
                            } else {
                                selectedSpecsIdList.add(curItem);
                            }
                        }
                        break;
                        case 3: {
                            if (curItem.getLevel() == selectedSpecsIdList.get(0).getLevel()) {
                                selectedSpecsIdList.set(0, curItem);
                                //更新本行
                                updateCurSelectRow(curItem);
                                int adapterPos = getItemAdapterPos(selectedSpecsIdList.get(1).getLevel());
                                //更新第二次选择的行
                                updateOtherRow(curItem, adapterPos);
                                // 如果第二次选择的行仍有匹配 和一组合 更新第三个选择的行
                                if (stillHasChecked(adapterPos)) {
                                    updateThirdSelectedRowByTwoBean(selectedSpecsIdList.get(0), selectedSpecsIdList.get(1));
                                }
                            } else if (curItem.getLevel() == selectedSpecsIdList.get(1).getLevel()) {
                                selectedSpecsIdList.set(1, curItem);
                                //更新本行
                                updateCurSelectRow(curItem);
                                //和一组合 更新第三行
                                Log.e(TAG, "onCheckChanged: ojjjj");
                                updateThirdSelectedRowByTwoBean(selectedSpecsIdList.get(0), selectedSpecsIdList.get(1));
                            } else if (curItem.getLevel() == selectedSpecsIdList.get(2).getLevel()) {
                                selectedSpecsIdList.set(2, curItem);
                                // 更新本行
                                updateCurSelectRow(curItem);
                            }
                        }
                        break;
                    }
                }
                break;
            }
            if (isSelectAllSpecs()) {
                doAfterSelectAllSpecs();
            }
        } else {
            specsTv.setText("");
            switch (specsTypeCount) {
                case 1: {
                    selectedSpecsIdList.clear();
                }
                break;
                case 2: {
                    int removePos = getRemovePos(event.getItem());
                    if (removePos != -1) {
                        selectedSpecsIdList.remove(removePos);
                        if (selectedSpecsIdList.size() == 0) {
                            //恢复所有checkbox 状态
                            recoverAllRow();
                        } else {
                            if (removePos == 0) {
                                letOtherRowBeFirst(selectedSpecsIdList.get(0).getLevel() - 1);
                            }
                        }
                    }
                }
                break;
                case 3: {
                    int removePos = getRemovePos(event.getItem());
                    if (removePos != -1) {
                        selectedSpecsIdList.remove(removePos);
                        if (selectedSpecsIdList.size() == 0) {
                            //恢复所有checkbox 状态
                            recoverAllRow();
                        } else {
                            if (removePos == 1) {
                                if (selectedSpecsIdList.size() == 2) {
                                    updateOtherRow(selectedSpecsIdList.get(0), getItemAdapterPos(selectedSpecsIdList.get(1).getLevel()));
                                }
                            } else if (removePos == 0) {
                                letOtherRowBeFirst(selectedSpecsIdList.get(0).getLevel() % 3);
                                if (selectedSpecsIdList.size() == 2) {
                                    updateOtherRow(selectedSpecsIdList.get(0), getItemAdapterPos(selectedSpecsIdList.get(1).getLevel()));
                                }
                            }
                        }
                    }
                }
                break;
            }
        }
    }

    //更新当前点击选择的行
    private void updateCurSelectRow(SpecsDataBean.SpecsBean.ItemsBean item) {
        int curPos = getItemAdapterPos(item.getLevel());
        SpecsItemAdapter curAdapter = specsChooseAdapter.getItemAdapterList().get(curPos);
        for (int i = 0; i < curAdapter.getData().size(); i++) {
            ZzCheckBox cb = (ZzCheckBox) curAdapter.getViewByPosition(i, R.id.cb_specs);
            if (cb != null && cb.isChecked()) {
                SpecsDataBean.SpecsBean.ItemsBean bean = curAdapter.getData().get(i);
                if (bean != null && bean.getItemid() != item.getItemid()) {
                    if (cb.isEnabled()) {
                        cb.setChecked(false);
                    }
                }
            }
        }
    }

    private int getItemAdapterPos(int level) {
        return specsTypeCount == 2 ? level - 1
                : specsTypeCount == 3 ? level % 3 : 0;
    }

    //根据给定的 item 和 目标level 更新 level 所在的行
    private void updateOtherRow(SpecsDataBean.SpecsBean.ItemsBean item, int adapterPos) {
        SparseArray<RelativeBean> relativeBeanSparseArray
                = relativeSparses.get(item.getItemid());
        SpecsItemAdapter otherAdapter = specsChooseAdapter.getItemAdapterList().get(adapterPos);
        //根据关系列表,刷新其他属性行的状态(enable状态)
        List<SpecsDataBean.SpecsBean.ItemsBean> itemsBeans = otherAdapter.getData();
        for (int i = 0, length = itemsBeans.size(); i < length; i++) {
            ZzCheckBox cb = (ZzCheckBox) otherAdapter.getViewByPosition(i, R.id.cb_specs);
            if (cb != null) {
                if (relativeBeanSparseArray.get(itemsBeans.get(i).getItemid()) == null) {
                    if (cb.isChecked()) {
                        cb.setChecked(false);
                        int removePos = getRemovePos(itemsBeans.get(i));
                        if (removePos != -1) {
                            selectedSpecsIdList.remove(removePos);
                        }
                    }
                    cb.setEnabled(false);
                } else {
                    if (!cb.isEnabled()) {
                        cb.setEnabled(true);
                    }
                }
            }
        }
    }

    private int getRemovePos(SpecsDataBean.SpecsBean.ItemsBean item) {
        for (int i = 0, length = selectedSpecsIdList.size(); i < length; i++) {
            if (item.getLevel() == selectedSpecsIdList.get(i).getLevel()) {
                return i;
            }
        }
        return -1;
    }

    //属性行有三行的情况下 更新其他未被选中的两行
    private void updateOtherTwoRow(SpecsDataBean.SpecsBean.ItemsBean item) {
        int notPos = item.getLevel() % 3;
        for (int i = 0, length = specsChooseAdapter.getItemAdapterList().size(); i < length; i++) {
            if (i != notPos) {
                updateOtherRow(item, i);
            }
        }
    }

    private void updateThirdRowByTwoBean(SpecsDataBean.SpecsBean.ItemsBean item1, SpecsDataBean.SpecsBean.ItemsBean item2) {
        Set<String> specsSet = new HashSet<>();
        for (int i = 0, length = optionsBeanList.size(); i < length; i++) {
            specsSet.add(optionsBeanList.get(i).getSpecs());
        }
        int adapterPos = getItemAdapterPos(6 - item1.getLevel() - item2.getLevel());
        SpecsItemAdapter adapter = specsChooseAdapter.getItemAdapterList().get(adapterPos);
        List<SpecsDataBean.SpecsBean.ItemsBean> dataList = adapter.getData();
        for (int i = 0, length = dataList.size(); i < length; i++) {
            ZzCheckBox cb = (ZzCheckBox) adapter.getViewByPosition(i, R.id.cb_specs);
            if (cb != null) {
                String specsStr = connectSpecsStr(item1, item2, dataList.get(i));
                cb.setEnabled(specsSet.contains(specsStr));
            }
        }
    }

    private void updateThirdSelectedRowByTwoBean(SpecsDataBean.SpecsBean.ItemsBean item1, SpecsDataBean.SpecsBean.ItemsBean item2) {
        Set<String> specsSet = new HashSet<>();
        for (int i = 0, length = optionsBeanList.size(); i < length; i++) {
            specsSet.add(optionsBeanList.get(i).getSpecs());
        }
        int adapterPos = getItemAdapterPos(6 - item1.getLevel() - item2.getLevel());
        SpecsItemAdapter adapter = specsChooseAdapter.getItemAdapterList().get(adapterPos);
        List<SpecsDataBean.SpecsBean.ItemsBean> dataList = adapter.getData();
        for (int i = 0, length = dataList.size(); i < length; i++) {
            ZzCheckBox cb = (ZzCheckBox) adapter.getViewByPosition(i, R.id.cb_specs);
            if (cb != null) {
                String specsStr = connectSpecsStr(item1, item2, dataList.get(i));
                boolean isContain = specsSet.contains(specsStr);
                if (!isContain && cb.isChecked()) {
                    cb.setChecked(false);
                    int removePos = getRemovePos(dataList.get(i));
                    if (removePos != -1) {
                        selectedSpecsIdList.remove(removePos);
                    }
                }
                cb.setEnabled(isContain);
            }
        }
    }

    private String connectSpecsStr(SpecsDataBean.SpecsBean.ItemsBean... items) {
        if (items.length == 3) {
            SpecsDataBean.SpecsBean.ItemsBean tmpItem = null;
            for (int i = 0, length = items.length; i < length; i++) {
                for (int j = i + 1; j < length; j++) {
                    if (items[i].getLevel() > items[j].getLevel()) {
                        tmpItem = items[i];
                        items[i] = items[j];
                        items[j] = tmpItem;
                    }
                }
            }
            return items[2].getItemid() + "_" + items[0].getItemid() + "_" + items[1].getItemid();
        } else {
            return "error";
        }
    }

    private boolean stillHasChecked(int adapterPos) {
        SpecsItemAdapter adapter = specsChooseAdapter.getItemAdapterList().get(adapterPos);
        for (int i = 0, length = adapter.getData().size(); i < length; i++) {
            ZzCheckBox cb = (ZzCheckBox) adapter.getViewByPosition(i, R.id.cb_specs);
            if (cb != null) {
                if (cb.isEnabled() && cb.isChecked()) {
                    return true;
                }
            }
        }
        return false;
    }

    //恢复所有行的状态
    private void recoverAllRow() {
        for (int i = 0, length = specsChooseAdapter.getItemAdapterList().size(); i < length; i++) {
            letOtherRowBeFirst(i);
        }
    }

    private void letOtherRowBeFirst(int adapterPos) {
        SpecsItemAdapter adapter = specsChooseAdapter.getItemAdapterList().get(adapterPos);
        for (int j = 0, jLength = adapter.getData().size(); j < jLength; j++) {
            ZzCheckBox cb = (ZzCheckBox) adapter.getViewByPosition(j, R.id.cb_specs);
            if (cb != null) {
                if (!cb.isEnabled()) {
                    cb.setEnabled(true);
                }
            }
        }
    }
}
